package com.wxy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxy.common.R;
import com.wxy.domain.Plant;
import com.wxy.domain.Student;
import com.wxy.domain.Teacher;
import com.wxy.domain.User;
import com.wxy.service.PlantService;
import com.wxy.service.StudentService;
import com.wxy.service.TeacherService;
import com.wxy.util.QrCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/plant")
public class PlantController {

    @Value("${zupeimiao.path}")
    private String basePath;

    //学生
    @Autowired
    private StudentService studentService;

    //老师
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private PlantService plantService;

    /**
     * 判断是学生还是老师还是管理员
     */

    @GetMapping("/verify")
    public int verify(HttpServletRequest request){
        //学生
        Long userid1 = (Long) request.getSession().getAttribute("student");
        if (userid1 != null)
            return 1;
        //老师
        Long userid2 = (Long) request.getSession().getAttribute("teacher");
        if (userid2 != null)
            return 2;
        //管理员
        String root  = (String) request.getSession().getAttribute("root");
        if (root != null)
            return 3;
        return -1;
    }
    @PostMapping("/student/session")
    public R<String> ssession(@RequestBody Student student, HttpSession session){
        session.setAttribute("student",student.getSusername());
        return R.success("ok");
    }
    @PostMapping("/teacher/session")
    public R<String> tsession(@RequestBody Teacher teacher, HttpSession session){
        session.setAttribute("teacher",teacher.getTusername());
        return R.success("ok");
    }
    @PostMapping("/root/session")
    public R<String> session(@RequestBody User user, HttpSession session){
        session.setAttribute("root",user.getUsername());
        return R.success("ok");
    }
    /**
     * 展示所有数据（老师可以看班里所有同学的信息，学生只能看自己的信息）
     * @param request
     */

    @GetMapping
    public R<List<Plant>> getAll(HttpServletRequest request) {
        if(verify(request) == -1){
            return R.error("当前未登录");
        }
        else if (verify(request) == 3){
            log.info("是管理员");
            return R.success(plantService.list());
        }
        else if(verify(request) == 1)
        {
            log.info("是学生");
            Long userid1 = (Long) request.getSession().getAttribute("student");
            LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Plant::getWhoPlantId,userid1);
            List<Plant> list = plantService.list(queryWrapper);
            //log.info(list.toString());
            return R.success(list);
        }
        else if(verify(request) == 2)
        {
            log.info("是老师");
            Long userid2 = (Long) request.getSession().getAttribute("teacher");
            LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Plant::getTeacherId,userid2);
            List<Plant> list = plantService.list(queryWrapper);

//            LambdaQueryWrapper<Student> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(Student::getTusername,userid2);
//            List<Student> list1 = studentService.list(queryWrapper1);
//            List<Plant> list = plantService.list(queryWrapper);
//            //添加老师学生的数据
//            for(Student stu:list1){
//                queryWrapper.eq(Plant::getWhoPlantId,stu.getSusername());
//                Plant plaData = plantService.getOne(queryWrapper);
//                if(plaData!=null)
//                    list.add(plaData);
//            }
            //添加老师自己的数据
            LambdaQueryWrapper<Plant> queryWrapper3 = new LambdaQueryWrapper();
            queryWrapper3.eq(Plant::getWhoPlantId,userid2);
            List<Plant> plaData = plantService.list(queryWrapper3);
            if (plaData!=null)
                list.addAll(plaData);
            //log.info(list.toString());
            return R.success(list);
        }
        return null;
    }
    //老师或学生添加数据时需要填写的父类id
    @GetMapping("/getpid")
    public R<List>getParentId(HttpServletRequest request){
        List<Integer>pid = new ArrayList<>();
        if(verify(request)==1){
            log.info("是学生");
            Long userid1 = (Long) request.getSession().getAttribute("student");
            LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Plant::getWhoPlantId,userid1);
            List<Plant> list1 = plantService.list(queryWrapper);
            for (Plant plant : list1){
                pid.add(plant.getId());
            }
        }
        if (verify(request)==2){
            log.info("是老师");
            Long userid2 = (Long) request.getSession().getAttribute("teacher");
            LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Plant::getTeacherId,userid2);
            List<Plant> list2 = plantService.list(queryWrapper);
            for (Plant plant : list2){
                pid.add(plant.getId());
            }
        }
        return R.success(pid);
    }

    /**
     * 添加数据
     * @param plant
     * @return
     */
    @PostMapping
    public R<String> add(HttpServletRequest request,@RequestBody Plant plant){
        if(verify(request) == -1){
            return R.error("未登录!");
        }
        if(verify(request) == 1){
            LambdaQueryWrapper<Student>queryWrapper = new LambdaQueryWrapper<>();
            log.info("是学生");
            queryWrapper.eq(Student::getSusername,(Long)request.getSession().getAttribute("student"));
            Student stu = studentService.getOne(queryWrapper);
            //填充已有信息
            plant.setWhoPlant(stu.getSname());
            plant.setWhoPlantId(stu.getSusername());
            plant.setDate(LocalDateTime.now());
            plant.setTeacherId(stu.getTusername());
        }
        if(verify(request) == 2){
            log.info("是老师");
            LambdaQueryWrapper<Teacher>queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teacher::getTusername,(Long)request.getSession().getAttribute("teacher"));
            Teacher tch = teacherService.getOne(queryWrapper);
            plant.setWhoPlant(tch.getTname());
            plant.setWhoPlantId(tch.getTusername());
            plant.setDate(LocalDateTime.now());
            plant.setTeacherId(tch.getTusername());
        }
        //保存于数据库中
        plantService.save(plant);
        return R.success("添加成功");
    }

    //修改植物的信息
    @PutMapping
    public R<String>update(@RequestBody Plant plant){
        LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Plant::getId,plant.getId());
        plantService.update(plant,queryWrapper);
        log.info("修改成功");
        return R.success("修改成功");
    }

    /**
     * 根据id获取对应的植物信息进行回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Plant>getById(@PathVariable Integer id){
        Plant plant = plantService.getById(id);
        return R.success(plant);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<String>deleteById(@PathVariable Integer id){
        boolean flag  = plantService.removeById(id);
        return flag?R.success("删除成功"):R.error("业务繁忙");
    }

    /**
     * 根据植物的id生成对应的二维码，并存储于服务器中进行保存
     * @param request
     * @param response
     * @param plantId
     */
    @GetMapping ("/getcode/{plantId}")
    public void createQrCode(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer plantId){
        StringBuffer url = request.getRequestURL();
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtils.encode(plantId.toString(), basePath + "img.png", "./QRcode", true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String fileName = plantId.toString() + ".png";
        try {
            //输入流
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + fileName));
            //输出流，通过输出流写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[]bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id（String）获取植物的数据
     * @param id
     * @return
     */
    @PostMapping("/getcode")
    public R<Plant> getcode(@RequestBody String id){
        JSONObject stuObj = JSON.parseObject(id);
        id = stuObj.getString("id");
        int plantId = Integer.parseInt(id);
        Integer plan = new Integer(plantId);
        LambdaQueryWrapper<Plant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Plant::getId,plan);
        Plant one = plantService.getOne(queryWrapper);
        return R.success(one);
    }

}
